package com.sh.data.engine.common.util.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.exception.ExcelGenerateException;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.sh.data.engine.common.constants.HttpStatus;
import com.sh.data.engine.common.constants.code.BizCodes;
import com.sh.data.engine.common.exception.BusinessException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author : fuchen
 * @date : 2021/12/23 14:55
 */
@Slf4j
public class EasyExcelUtil {
    public static void exportExcel(
        HttpServletResponse response, String fileName, List<List<String>> dataList) {
        try {
            response.setHeader(
                "Content-disposition",
                "attachment; filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            OutputStream outputStream = response.getOutputStream();
            ExcelWriter writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, false);
            WriteSheet sheet = EasyExcel.writerSheet("sheet").build();
            writer.write(dataList, sheet);
            writer.finish();
            outputStream.flush();
        } catch (IOException | ExcelGenerateException e) {
            log.error("导出异常:", e);
            throw new BusinessException(BizCodes.EXPORT_EXCEL_FILE_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 模板下载通用方法
     *
     * @param response
     * @param templateName
     * @param templateNameCn
     */
    public static void importExcelDownload(
        HttpServletResponse response, String templateName, String templateNameCn) {
        InputStream importStream = null;
        try {
            response.setHeader(
                "Content-disposition",
                "attachment; filename=" + URLEncoder.encode(templateNameCn + ".xlsx", "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            importStream = EasyExcelUtil.class.getClassLoader().getResourceAsStream(templateName);
            if (importStream == null) {
                throw new BusinessException(BizCodes.TEMPLATE_FILE_NOT_EXISTS, HttpStatus.BAD_REQUEST);
            }
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = importStream.read(buff)) > 0) {
                response.getOutputStream().write(buff, 0, len);
            }
            response.flushBuffer();
        } catch (Exception e) {
            log.error("模板文件下载异常:", e);
            throw new BusinessException(BizCodes.TEMPLATE_FILE_DOWNLOAD_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(importStream);
        }
    }

    /**
     * 单sheet导入
     *
     * @param file
     * @param headRowNumber title行数
     * @return
     */
    public static List<List<String>> singleSheetImport(MultipartFile file, int headRowNumber) {
        try {
            if (headRowNumber < 0) {
                headRowNumber = 0;
            }
            ExcelStringListener listener = new ExcelStringListener();
            ExcelReader excelReader =
                EasyExcelFactory.read(file.getInputStream(), null, listener)
                    .headRowNumber(headRowNumber)
                    .build();
            excelReader.read();
            List<List<String>> dataList = listener.getDataList();
            excelReader.finish();
            return dataList;
        } catch (Exception e) {
            log.error("导入异常:", e);
            throw new BusinessException(BizCodes.IMPORT_EXCEL_FILE_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 读取
     *
     * @param dataList
     * @param index    list下标 从0开始
     * @return
     */
    public static String getValueByIndex(List<String> dataList, int index) {
        if (CollectionUtils.isEmpty(dataList)) {
            return null;
        }
        if (dataList.size() >= index + 1) {
            return dataList.get(index);
        }
        return null;
    }
}
